import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
// import type { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import * as icons from '@ant-design/icons';
import { BasicLayoutProps } from '@ant-design/pro-layout';
import { Models } from '@@/plugin-model/useModel';
//请求层loading
import ContextLoading from '@/PublicComponents/Context/contextLoading';
import { services } from '@/network/api';
import logo from '@/asset/img/logo.png';

import React from 'react';
// @ts-ignore
type Routes = IRoute[];

type RunTimeLayoutConfig = (initData: Models<'@@initialState'>) => BasicLayoutProps & {
  childrenRender?: (dom: JSX.Element) => React.ReactNode;
  unAccessible?: JSX.Element;
  noFound?: JSX.Element;
};

const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: any;
  fetchUserInfo?: () => Promise<any>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await services.currentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}
//初始化路由
let initialRoutes: any = {};
let initialState: any = {};
export function patchRoutes(...arg: any) {
  function mapNewRoute(routes: any) {
    routes?.map((route: any) => {
      route?.name && (route.name = initialRoutes[route.path]?.name);
      route.newIcon = initialRoutes[route.path]?.icon;
      route.accessList = initialRoutes[route.path]?.access;
      route.accessBtnList = initialRoutes[route.path]?.children;
      route.checkBtn = function (field: string | 'add' | 'delete' | 'edit') {
        let routeBtn = this?.accessBtnList?.filter((item: any) => {
          return item.path === field;
        })?.[0];
        return routeBtn?.access?.some((item: any) => {
          return initialState?.data?.access.some((_item: any) => {
            return _item.field === item.field;
          });
        });
      };
      route.routes && mapNewRoute(route.routes);
    });
  }
  mapNewRoute(arg[0].routes);
  arg[0].routes;
}
export async function render(oldRender: any) {
  initialState = await services.currentUser();
  let res = await services.getRouteTree();
  res?.data?.map((route: any) => {
    initialRoutes[route.path] = route;
  });
  oldRender();
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout11
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    childrenRender: (children) => {
      return (
        <>
          <ContextLoading>{children}</ContextLoading>
        </>
      );
    },
    menuItemRender: (item, dom: any) => {
      return (
        <Link to={item.path}>
          <div>
            {!!item?.newIcon && React.createElement(icons[item?.newIcon])}
            {dom}
          </div>
        </Link>
      );
    },
    subMenuItemRender: (item, dom) => {
      return (
        <div>
          {!!item?.newIcon && React.createElement(icons[item?.newIcon])}
          {dom}
        </div>
      );
    },
    menu: {
      locale: false,
    },
    title: `CRM 销管系统`,
    logo,
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
    SettingDrawer: true,
  };
};
